<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-7-29
 * Time: 上午9:40
 */

namespace common\models\db;

use common\members\wodrow\validators\Loop;
use yii\helpers\ArrayHelper;

/**
 * Class Menu
 * @package common\models\db
 *
 * @property Menu $p
 * @property Menu[] $menus
 * @property Yii2App $yii2App
 * @property User $createdBy
 * @property RoleMenu[] $roleMenus
 * @property Role[] $roles
 */
class Menu extends \common\models\db\second\Menu
{
    const STATUS_DEFAULT = 0;

    public function rules()
    {
        $p = parent::rules();
        $add = [
//            ['root', Loop::class],
            ['sort', 'default', 'value' => 0],
        ];
        $r = ArrayHelper::merge($p, $add);
        return $r;
    }

    /**
     * @param array $menus
     * @return array
     */
    public static function generateAdminlteLeftMenuTreeItems($menus)
    {
        foreach ($menus as $k => $v){
            $menus[$k]['label'] = $v['name'];
            $menus[$k]['url'] = [$v['uri']];
            if ($v['root'] == $v['id'])$menus[$k]['root'] = null;
            unset($menus[$k]['active']);
        }
        $tree = \common\components\tools\ArrayHelper::toTree($menus, 'id', 'root', 'items');
        return $tree;
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getP()
    {
        return $this->hasOne(Menu::className(), ['id' => 'root']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMenus()
    {
        return $this->hasMany(Menu::className(), ['root' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getYii2App()
    {
        return $this->hasOne(Yii2App::className(), ['id' => 'yii2_app_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCreatedBy()
    {
        return $this->hasOne(User::className(), ['id' => 'created_by']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRoleMenus()
    {
        return $this->hasMany(RoleMenu::className(), ['menu_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRoles()
    {
        return $this->hasMany(Role::className(), ['id' => 'role_id'])->viaTable('{{%role_menu}}', ['menu_id' => 'id']);
    }
}